package com.yuntsg.nnsfcp.util.httpclient.gcrclient;

import com.yuntsg.nnsfcp.common.utils.StringUtil;
import com.yuntsg.nnsfcp.util.EIHttpClient.ProxyInfo;
import com.yuntsg.nnsfcp.util.HttpClientUtil;
import com.yuntsg.nnsfcp.util.httpclient.HttpClientConfig;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GcrHttpClientUtil {

    /**
     * 转化各个httpclient返回的html
     */
    public static String parsingHtml(CloseableHttpResponse responce) throws Exception {
        String html = null;
        HttpEntity entity = responce.getEntity();
        if (entity != null) {
            html = EntityUtils.toString(entity, "UTF-8");
            html = html.replace("&nbsp;", " ");
        }
        return html;
    }

    /**
     * 将各个httpclient获取的HttpResponse转化为相应的pdf
     */

    /**
     * 根据各个资源的路径生成对应的pdf
     */
    public static void createFile(String filePath, String fileName, byte[] content)
            throws IOException {
        File folder = new File(filePath);
        if (!folder.exists() && !folder.isDirectory()) {
            System.out.println("文件夹路径不存在，创建路径:" + filePath);
            folder.mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(filePath + "/" + fileName);
        fos.write(content);
        fos.close();
    }

    /**
     * 生成用户凭证的方法
     */
    public static CredentialsProvider build(ProxyInfo pi) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(pi.getIp(), Integer.parseInt(pi.getPort())), (Credentials) new UsernamePasswordCredentials(pi.getUserName(), pi.getPassword()));
        return credsProvider;
    }

    /**
     * 生成代理ip的请求配置的方法
     */
    public static RequestConfig buildRequestConfigure(ProxyInfo pi, Boolean redirectFlag) {
        int timeout = pi.getTimeout();
        if (timeout == 0) {
            timeout = HttpClientConfig.TIME_OUT;
        }
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(timeout).setConnectTimeout(timeout).setRedirectsEnabled(redirectFlag)
                .setProxy(new HttpHost(pi.getIp(), Integer.parseInt(pi.getPort())))
                .build();
        return requestConfig;
    }

    /**
     * 创建不需要代理服务器的请求配置--redirect为是否允许循环跳转--默认为true
     */
    public static RequestConfig buildNoProxyRequestConfigure(ProxyInfo pi, boolean redirectFlag) {
        int timeout = pi.getTimeout();
        if (timeout == 0) {
            timeout = HttpClientConfig.TIME_OUT;
        }
        RequestConfig requestConfig = RequestConfig.custom().setRedirectsEnabled(redirectFlag)
                .setSocketTimeout(timeout).setConnectTimeout(timeout).build();
        return requestConfig;
    }


    /**
     * 通过代理信息生成相应的检索配置信息
     */
    public static GcrHttpClientConfig getSearConfig(ProxyInfo pi, String url, String refer, String host, boolean redireFlag) {
        GcrHttpClientConfig config = new GcrHttpClientConfig();
        config.setUrl(url);
        config.setHost(host);
        config.setRefer(refer);
        Map<String, String> headerMap = new HashMap<>();
        if (!StringUtil.isEmpty(host)) {
            headerMap.put(HttpHeaders.HOST, host);
        }
        if (!StringUtil.isEmpty(refer)) {
            headerMap.put(HttpHeaders.REFERER, refer);
        }
        config.setHeaderMap(headerMap);
        if (pi == null || pi.getSwitchType() == null || pi.getSwitchType().equals("1")) {
            CredentialsProvider credsProvider = HttpClientUtil.build(pi);
            RequestConfig requestConfig = HttpClientUtil.buildRequestConfigure(pi, redireFlag);
            config.setCredsProvider(credsProvider);
            config.setRequestConfig(requestConfig);
        } else {
            RequestConfig requestConfig = HttpClientUtil.buildNoProxyRequestConfigure(pi, redireFlag);
            config.setRequestConfig(requestConfig);
        }
        return config;
    }


    public static GcrHttpClientConfig getSearConfig(String url, String refer, String host, boolean redireFlag) {
        GcrHttpClientConfig config = new GcrHttpClientConfig();
        config.setUrl(url);
        config.setHost(host);
        config.setRefer(refer);
        Map<String, String> headerMap = new HashMap<>();
        if (!StringUtil.isEmpty(host)) {
            headerMap.put(HttpHeaders.HOST, host);
        }
        if (!StringUtil.isEmpty(refer)) {
            headerMap.put(HttpHeaders.REFERER, refer);
        }
        config.setHeaderMap(headerMap);
//        if(pi.getSwitchType()==null||pi.getSwitchType().equals("1")) {
//            CredentialsProvider credsProvider = HttpClientUtil.build(pi);
//            RequestConfig requestConfig = HttpClientUtil.buildRequestConfigure(pi, redireFlag);
//            config.setCredsProvider(credsProvider);
//            config.setRequestConfig(requestConfig);
//        }else{
//            RequestConfig requestConfig = HttpClientUtil.buildNoProxyRequestConfigure(pi,redireFlag);
//            config.setRequestConfig(requestConfig);
//        }
        return config;
    }


    /**通过session获取相应的代理信息*/
//    public static ProxyInfo getProxy(HttpSession session, int proxyId){
//        Map<Integer,ProxyInfo> proxyMap = (Map<Integer,ProxyInfo>)session.getAttribute("proxyMap");
//        if(proxyMap==null){
//            String gid = (String)session.getAttribute("gid");
//            if(!StringUtil.isEmpty(gid)) {
//                Map<Integer, ProxyInfo> map = myinfoDao.getResourceProxy(gid);
//                session.setAttribute("proxyMap", map);
//            }
//        }
//        ProxyInfo pi = proxyMap.get(proxyId);
//        System.out.println("代理内容:"+pi.toString());
//        return pi;
//    }

    /**
     * 打印cookie查看问题的方法
     */
    public static void printCookie(BasicCookieStore bcs) {
        List<Cookie> list = bcs.getCookies();
        for (Cookie c : list) {
            System.out.println("cookie信息:" + c.toString());
        }
    }

}
